<template>
  <j-modal :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading" switchFullscreen @ok="handleOk"
    @cancel="handleCancel" cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name" label="视频名称">
          <a-input placeholder="请输入视频名称" v-model="model.name" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="videoSetId" label="视频专辑">
          <a-select allow-clear show-search style="width: 200px" :default-active-first-option="false" :show-arrow="false"
            :filter-option="false" :not-found-content="null" @search="handleSearch" @change="handleChange"
            v-model="model.videoSetId" placeholder="请选择专辑">
            <a-select-option :value="item.id" v-for="(item, index) in videoSetList" :key="index">
              {{ item.setName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="coverLevel" label="预览图（水平）">
          <boboCropper v-model="model.coverLevel" :aspectRatio="225 / 120"></boboCropper>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="coverVertical" label="预览图（垂直）">
          <boboCropper v-model="model.coverVertical" :aspectRatio="90 / 120"></boboCropper>
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="playUrl" label="视频地址">
          <a-upload accept="video/*" name="file" :multiple="true" :action="uploadVideoAction" :headers="headers"
            :file-list="videoList" @change="handleVideoChange" :before-upload="beforeVideoUpload">
            <a-button> <a-icon type="upload" /> Click to Upload </a-button>
          </a-upload>
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="introductionShort" label="简短简介">
          <a-input placeholder="请输入简短简介" v-model="model.introductionShort" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sort" label="排序">
          <a-input-number v-model="model.sort" />
        </a-form-model-item>
        <!-- <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="videoDuration" label="视频时长 秒">
          <a-input-number v-model="model.videoDuration" />
        </a-form-model-item> -->
      </a-form-model>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import moment from "moment"
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: "VideoDOModal",
  data() {
    return {
      title: "操作",
      videoList: [],
      headers: {},
      imgLoading: false,
      uploadAction: '',
      uploadVideoAction: '',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      confirmLoading: false,
      videoSetList: [],
      validatorRules: {
        name: [
          { required: true, message: '视频名称不允许为空', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入3-10个字符', trigger: 'blur' },
        ],
        videoSetId: [
          { required: true, message: '专辑不允许为空', trigger: 'blur' },
        ],
        sort: [
          { required: true, message: '排序不允许为空', trigger: 'blur' },
        ],
        introductionShort: [
          { required: true, message: '长简介不允许为空', trigger: 'blur' },
        ],
        coverLevel: [
          { required: true, trigger: 'change', validator: this.uploadCoverLevelChange },
        ],
        coverVertical: [
          { required: true, trigger: 'change', validator: this.uploadCoverVerticalChange },
        ],
        playUrl: [
          { required: true, trigger: 'change', validator: this.uploadCoverVideoChange },
        ],
      },
      url: {
        add: "/admin/videoDO/add",
        edit: "/admin/videoDO/edit",
        videoSetAll: "/admin/videoSetDO/videoSetAll",
      },
    }
  },
  created() {
  },
  methods: {
    add() {
      //初始化默认值
      this.edit({});
    },
    edit(record) {
      this.queryVideoSetList();
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = { "X-Access-Token": token }
      this.uploadAction = window._CONFIG['domianURL'] + '/upload/file'
      this.uploadVideoAction = window._CONFIG['domianURL'] + '/upload/uploadVideoToM3U8'
      this.videoList = [];
      this.model = Object.assign({}, record);
      if (this.model.playUrl) {
        let video = {
          status: "done",
          type: "video/mp4",
          uid: "vc-upload-1682701433890-6",
          name: this.model.playUrl,
          url: this.model.playUrl
        }
        this.videoList.push(video);
      }
      this.visible = true;
    },
    close() {
      this.$emit('close');
      this.visible = false;
      this.$refs.form.clearValidate();
    },
    beforeVideoUpload(file, files) {
      let isFileType = true // 文件类型
      let isFileSize = true // 文件大小
      var url = URL.createObjectURL(file)
      var audioElement = new Audio(url)
      var duration = parseInt(audioElement.duration)
      audioElement.addEventListener('loadedmetadata', () => {
        duration = parseInt(audioElement.duration) // 时长为秒，取整
        console.log(parseInt(audioElement.duration), '上传视频的时长')
        this.model.videoDuration = duration;
        this.$emit('cTime', duration)
      })
    },
    handleOk() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.close();
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        } else {
          return false;
        }
      })
    },
    queryVideoSetList(value) {
      let param = {
      }
      if (value) {
        param = {
          setName: value
        }
      } else {
        param = {
          limit: 40
        }
      }

      getAction(this.url.videoSetAll, param).then((res) => {
        if (res.success) {
          this.videoSetList = res.result;
        } else {
          that.$message.warning(res.message);
        }
      })
    },
    handleCancel() {
      this.close()
    },
    handleSearch(value) {
      this.queryVideoSetList(value);
    },
    handleChange(value) {
      this.queryVideoSetList(value);
    },
    // 自定义预览图校验
    uploadCoverLevelChange(rule, value, callback) {
      if (!this.model.coverLevel || this.model.coverLevel == '') {
        return callback(new Error('预览图片不允许为空~'));
      } else {
        return true;
      }
    },
    // 自定义预览图校验
    uploadCoverVerticalChange(rule, value, callback) {
      if (!this.model.coverVertical || this.model.coverVertical == '') {
        return callback(new Error('预览图片不允许为空~'));
      } else {
        return true;
      }
    },
    // 自定义预览视频校验
    uploadCoverVideoChange(rule, value, callback) {
      if (!this.model.playUrl || this.model.playUrl == '') {
        return callback(new Error('请上传视频~'));
      } else {
        return true;
      }
    },
    handleChangeImgCover(info) {
      if (info.file.status === 'uploading') {
        this.imgLoading = true;
        return;
      }
      if (info.file.status === 'done') {
        this.model.cover = info.file.response.result;;
        this.imgLoading = false;
        this.$forceUpdate();
      }
    },
    beforeUploadCover(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
    handleVideoChange(info) {
      let fileList = [...info.fileList];
      // 1. Limit the number of uploaded files
      //    Only to show two recent uploaded files, and old ones will be replaced by the new
      fileList = fileList.slice(-1);

      // 2. read from response and show file link
      fileList = fileList.map(file => {
        console.log(file, "file")
        if (file.response) {
          if (file.response.code == 200) {
            file.url = file.response.result;
            this.model.playUrl = file.response.result;
          } else {
            file.status = 'error';
          }

        }
        return file;
      });
      if (fileList.length == 0) {
        this.model.coverVideoUrl = '';
      }
      this.videoList = fileList;

    },
  }
}
</script>

<style lang="less" scoped></style>